package com.me.jingdongshop.ui.activity;

import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.me.common.base.BaseActivity;
import com.me.common.base.Const;
import com.me.common.base.Global;
import com.me.common.util.SharedPreUtil;
import com.me.jingdongshop.R;
import com.me.jingdongshop.dagger2.component.DaggerAddresstComponent;
import com.me.jingdongshop.dagger2.module.AddressFragmentModule;
import com.me.jingdongshop.model.bean.Address;
import com.me.jingdongshop.model.bean.LocationList;
import com.me.jingdongshop.model.protocol.IHttpService;
import com.me.jingdongshop.presenter.TestFragmentPre;
import com.me.jingdongshop.ui.adapter.CustomSpinnerArrayAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

/**
 * 进入地址管理界面(新增地址，编辑地址，删除地址)
 *
 * @author admin
 */
public class AddressManageActivity extends BaseActivity {
    public static final int RESULT_CODE = 01;

    //private Address mAddress;
    /**
     * 对地址进行增删改查的对象
     */
  /*  private AddressDao addressDao = GreenDaoHelper
            .getInstance().getDaoSession().getAddressDao();*/
    private String mUserName;
    private String mAddressDetail;
    private String mAddressPost;
    private android.widget.ImageButton btnBack;
    private TextView tvTitle;
    private android.widget.ImageButton addressSave;
    private EditText addressName;
    private EditText addressPhone;
    private EditText addressPost;
    private android.widget.Spinner spProvince;
    private android.widget.Spinner spCity;
    private android.widget.Spinner spArea;
    private EditText addressLocation;
    private String mAddressPhone;

    private ArrayAdapter<String> mProvinceAdapter;
    private ArrayAdapter<String> mCityAdapter;
    private ArrayAdapter<String> mAreaAdapter;
    private String mCurrentProviceName;
    private String mCurrentCityName;
    private String mCurrentCountyName;

    private Boolean isFirstLord = true;//判断是不是最近进入对话框

    @Override
    public int getLayoutRes() {
        return R.layout.activity_add_recipients_address;
    }

    @Override
    public void initView() {

        btnBack = (ImageButton) findViewById(R.id.btn_back);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        addressSave = (ImageButton) findViewById(R.id.address_save);
        addressName = (EditText) findViewById(R.id.address_name);
        addressPhone = (EditText) findViewById(R.id.address_phone);
        addressPost = (EditText) findViewById(R.id.address_post);
        spProvince = (Spinner) findViewById(R.id.spProvince);
        spCity = (Spinner) findViewById(R.id.spCity);
        spArea = (Spinner) findViewById(R.id.spArea);
        addressLocation = (EditText) findViewById(R.id.address_location);
        /**
         * 设置，省，市，县，的适配器，进行动态设置其中的值  begin
         */
        mProvinceAdapter = new CustomSpinnerArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, provinces, 10f);
        mProvinceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spProvince.setAdapter(mProvinceAdapter);

        mCityAdapter = new CustomSpinnerArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, citys, 10f);
        mCityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spCity.setAdapter(mCityAdapter);

        mAreaAdapter = new CustomSpinnerArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, countys, 10f);
        mAreaAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spArea.setAdapter(mAreaAdapter);
    }

    @Override
    public void initListener() {
        addressSave.setOnClickListener(this);
        //省的点击事件
        spProvince.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (mCurrentProviceName.equals(parent.getSelectedItem() + "")) {
                    return;
                }
                mCurrentProviceName = parent.getSelectedItem() + "";
                pre.getCity(provinceAddress.get(position).getId());
//                if (isFirstLord) {
//                    if (mAddress != null && !mAddress.equals("") && mAddressList.length > 1 && mAddressList.length < 3) {
//                        updateCitiesAndAreas(mCurrentProviceName, mAddressList[1], null);
//                    } else if (mAddress != null && !mAddress.equals("") && mAddressList.length >= 3) {
//                        updateCitiesAndAreas(mCurrentProviceName, mAddressList[1], mAddressList[2]);
//                    } else {
//                        updateCitiesAndAreas(mCurrentProviceName, null, null);
//                    }
//                } else {
//                    updateCitiesAndAreas(mCurrentProviceName, null, null);
//                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        spCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (mCurrentCityName.equals(parent.getSelectedItem() + "")) {
                    return;
                }
                mCurrentCityName = parent.getSelectedItem() + "";
                pre.getCounty(cityAddress.get(position).getId());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        spArea.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (mCurrentCountyName.equals(parent.getSelectedItem() + "")) {
                    return;
                }
                mCurrentCountyName = parent.getSelectedItem() + "";
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    @Inject
    TestFragmentPre pre;

    @Override
    public void initData() {
        DaggerAddresstComponent.builder()
                .addressFragmentModule(new AddressFragmentModule(this))
                .build().inject(this);
        pre.getLocation(0);
        // 获取上一个界面传过来的要编辑的地址
       /* mAddress = (Address) getIntent().getSerializableExtra(Const.KYE_BEAN);
        if (mAddress == null) {
            super.setPageTitle("新增地址");
        } else {
            super.setPageTitle("编辑地址");
            btnDeleteAddress.setVisibility(View.VISIBLE);//显示删除按钮
            //回显要编辑的地址数据
            fillDatas();
        }*/
    }

    /**
     * 回显要编辑的地址数据
     */
    private void fillDatas() {
       /* etName.setText(mAddress.getUsername());
        etPhone.setText(mAddress.getPhone());
        int sex = mAddress.getSex();
        if (sex == 1) {
            rbMale.setChecked(true);
        } else {
            rbFemale.setChecked(true);
        }
        tvAddress.setText(mAddress.getAddressName());
        etAddressDetail.setText(mAddress.getAddressDetail());*/
    }

    @Override
    public void onClick(View v, int id) {
        if (addressSave == v) {      // 保存地址
            onBtnSaveClick();
            return;
        }
        /*if (btnDeleteAddress == v) {      // 删除地址
           *//* addressDao.delete(mAddress);*//*
            finish();
            return;
        }*/
    }

    /**
     * 保存地址
     */
    private void onBtnSaveClick() {
        mUserName = addressName.getText().toString().trim();
        mAddressPhone = addressPhone.getText().toString();
        mAddressPost = addressPost.getText().toString().trim();
        mAddressDetail = addressLocation.getText().toString().trim();
        if (validate()) {// 校验数据的合法性
            // 保存地址到数据库中
            String uid = SharedPreUtil.getString(Global.mContext, Const.KEY_UID, "");
            uid = "20428";
            if (TextUtils.isEmpty(uid)) {
                Toast.makeText(this, "请登录", Toast.LENGTH_SHORT).show();
                return;
            }
            Map<String, String> map = new HashMap<>();
           // map.put("id", "222");
            map.put("name", mUserName);
            map.put("phoneNumber", mAddressPhone);
            map.put("province", mCurrentProviceName);
            map.put("city", mCurrentCityName);
            map.put("addressArea", mCurrentCountyName);
            map.put("addressDetail", mAddressDetail);
            map.put("zipCode", mAddressPost);
            map.put("isDefault", "1");
            pre.saveAddAddress(uid, map);
        }

    }

    /**
     * 校验数据的合法性，返回true表示校验通过
     *
     * @return
     */
    private boolean validate() {
        if (TextUtils.isEmpty(mUserName)) {
            showToast("用户不能为空");
            return false;
        }

        if (TextUtils.isEmpty(mAddressPost)) {
            showToast("邮编不能为空");
            return false;
        }
        if (!isMobileNO(mAddressPhone)) {
            showToast("请填写合法的手机号");
            return false;
        }
        if (TextUtils.isEmpty(mAddressDetail)) {
            showToast("收货地不能为空");
            return false;
        }
        return true;
    }

    /**
     * 是否是合法的电话号码
     */
    public boolean isMobileNO(String phone) {
        //"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，
        // "\\d{9}"代表后面是可以是0～9的数字，有9位。
        String telRegex = "[1][358]\\d{9}";
        return phone.matches(telRegex);
    }

    private List<String> provinces = new ArrayList<>();
    private List<Address.AreaListBean> provinceAddress = new ArrayList<>();
    private List<String> citys = new ArrayList<>();
    private List<Address.AreaListBean> cityAddress = new ArrayList<>();
    private List<String> countys = new ArrayList<>();

    @Override
    public void onHttpSuccess(int reqType, Message msg) {
        if (reqType == IHttpService.HTTP_LOCATION) {
            Address address = (Address) msg.obj;
            Address.AreaListBean areaListBean = address.getAreaList().get(0);
            mCurrentProviceName = areaListBean.getValue();
            pre.getCity(areaListBean.getId());
            for (Address.AreaListBean bean :
                    address.getAreaList()) {
                String value = bean.getValue();
                provinces.add(value);
                provinceAddress.add(bean);
            }
            mProvinceAdapter.notifyDataSetChanged();
        }
        if (reqType == IHttpService.HTTP_CITY) {
            //清空数据
            citys.clear();
            cityAddress.clear();
            Address address = (Address) msg.obj;
            if (address.getAreaList().size() < 1) {
                countys.clear();
                mCityAdapter.notifyDataSetChanged();
                mAreaAdapter.notifyDataSetChanged();
                return;
            }
            Address.AreaListBean areaListBean = address.getAreaList().get(0);
            mCurrentCityName = areaListBean.getValue();
            pre.getCounty(areaListBean.getId());
            for (Address.AreaListBean bean :
                    address.getAreaList()) {
                String value = bean.getValue();
                citys.add(value);
                cityAddress.add(bean);
            }
            mCityAdapter.notifyDataSetChanged();
        }
        if (reqType == IHttpService.HTTP_COUNTY) {
            //清空数据
            countys.clear();
            Address address = (Address) msg.obj;
            if (address.getAreaList().size() < 1) {
                return;
            }
            mCurrentCountyName = address.getAreaList().get(0).getValue();
            for (Address.AreaListBean bean :
                    address.getAreaList()) {
                String value = bean.getValue();
                countys.add(value);
            }
            mAreaAdapter.notifyDataSetChanged();
        }
        if (reqType == IHttpService.HTTP_SAVE_ADDRESS) {
            LocationList locationList = (LocationList) msg.obj;
            Toast.makeText(this, "设置成功", Toast.LENGTH_SHORT).show();
            setResult(RESULT_CODE);
        }
    }

    @Override
    public void onHttpError(int reqType, String error) {

    }
}
